﻿@using OSBIDE.Library
@using OSBIDE.Library.Models
@using OSBIDE.Web.Models.ViewModels
@using OSBIDE.Library.Events
@using OSBIDE.Web.Models
@using System.Collections.Generic
@model FeedViewModel
<section>
    @Html.ActionLink("Load earlier posts...", "Index", new { timestamp = Model.LastPollDate.AddHours(-10).Ticks, errorType = Model.SelectedErrorType.Id }, new { id = "load-old-posts" })
</section>
<div id="hidden-workspace">
</div>
<div id="hidden-updates-workspace" style="display: none;"></div>

<script type="text/javascript">

    $(document).ready(function () {

        //get recent feed items
        getRecentFeedItems();

        //get updates for current items
        getCurrentFeedItemUpdates();

        //display hidden 
        showLastHidden();

        //listen for clicks to load older messages
        $("#load-old-posts").click(function (e) {
            e.preventDefault();
            $("#load-old-posts").text("Loading...");
            var feedId = getOldestFeedId();
            $.ajax(
            {
                url: "@Url.Action("OldFeedItems", "Feed")",
                data: { id: feedId, count: 10, userId: "@Model.SingleUserId", errorType: "@Model.SelectedErrorType.Id" },
                dataType: "html",
                type: "GET",
                success: getOldPostsSuccess,
            }
            );
        });

        //disable footer selection
        $('.feed-item-footer').disableSelection();
    }
    );

    function expandComments(element) {
        element = "#" + element;
        if ($(element).find('.log-comment-single').length > 0) {
            if ($(element).css('display') == 'none') {
                $(element).css('display', 'block');
            }
            else {
                $(element).css('display', 'none')
            }
        }
    }

    function getOldPostsSuccess(html) {
        $("#load-old-posts").text("Load earlier posts...");
        var trimmed = $.trim(html);
        if (trimmed.length > 0) {
            $("#feed-items").append(html);
            parseDates();
            $(".feed-item-ajax:hidden.OldFeedItems").each(function (e) {
                $(this).removeClass("feed-item-ajax");
            });
        }
        else {
            $("#load-old-posts").text("No earlier posts available.");
        }
    }

    function showLastHidden() {
        var initialScrollHeight = $(document).scrollTop();
        var item = $(".feed-item-ajax:hidden").last();

        //if we're loading old items, 
        if (item.hasClass("OldFeedItems")) {
            item = $(".feed-item-ajax:hidden.OldFeedItems").first();
        }
        item.slideDown(
                {
                    duration: 600,
                    easing: "linear",
                    progress: function (animation, progress, remainingMs) {
                        if (initialScrollHeight > 50) {
                            $(document).scrollTop($(this).height() + initialScrollHeight);
                        }
                    }
                });
        setTimeout(showLastHidden, 4000);
    }

    function getOldestFeedId() {
        var lastId = $(".feed-item-single").last().attr("data-id");
        if (lastId == undefined) {
            lastId = "@(Model.LastLogId + 1)";
    }
    return lastId;
}

function getMostRecentFeedId() {
    var lastId = $(".feed-item-single").first().attr("data-id");
    if (lastId == undefined) {
        lastId = "@Model.LastLogId";
        }
        return lastId;
    }

    var lastUpdateCheck = "@Model.LastPollDate.Ticks";
    function getCurrentFeedItemUpdates() {
        var dataIds = Array();
        var i = 0;
        $(".feed-item-single").each(function (item) {
            //var lastPollTick = lastUpdateCheck;//$(this).find('.feed-item-comments').first().attr('data-lastPoleDate');
            dataIds[i] = { LogId: $(this).attr('data-id'), LastPollTick: lastUpdateCheck };
            i++;
        });
        $.ajax(
            {
                url: "@Url.Action("GetItemUpdates", "Feed")",
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(dataIds),
                dataType: "html",
                type: "POST",
                success: getCurrentFeedItemUpdatesSuccess,
                complete: function () { setTimeout(getCurrentFeedItemUpdates, 40000); }
            }
            );
    }

    function getCurrentFeedItemUpdatesSuccess(html) {

        var trimmed = $.trim(html);
        if (trimmed.length > 0) {

            //get all current log comments
            var dataIds = Array();
            $('.log-comment-single').each(function (index) {
                dataIds.push($(this).attr('data-id'));
            });


            $('#hidden-updates-workspace').append(html);
            parseDates();
            lastUpdateCheck = $('#last-poll-tick').val();

            //loop through children
            $('#hidden-updates-workspace').children('.log-comment-single').each(function (index) {
                if (dataIds.indexOf($(this).attr('data-id')) < 0) {
                    var commentsIdString = '#feed-item-comments-' + $(this).attr('data-logId');
                    if ($(commentsIdString).length > 0) {

                        //append the comment
                        $(commentsIdString).append(this);

                        //update comment count text
                        var commentCountIdString = '#expand-comments-' + $(this).attr('data-logId');
                        if ($(commentCountIdString).length > 0) {
                            var commentStr = $(commentsIdString).find('.log-comment-single').length + ' Comment(s)';
                            $(commentCountIdString).text(commentStr);
                        }
                    }
                }
            });
        }
        $('#hidden-updates-workspace').empty();
    }

    function getRecentFeedItems() {

        //find most recent log id
        var lastId = getMostRecentFeedId();
        $.ajax(
            {
                url: "@Url.Action("RecentFeedItems", "Feed")",
                data: { id: lastId, userId: "@Model.SingleUserId", errorType: "@Model.SelectedErrorType.Id" },
                dataType: "html",
                type: "GET",
                success: getRecentFeedItemsSuccess,
                complete: function () { setTimeout(getRecentFeedItems, 40000); }
            }
            );
    }

    function getRecentFeedItemsSuccess(html) {
        var trimmed = $.trim(html);
        if (trimmed.length > 0) {
            $("#hidden-workspace").append(html);
            parseDates();
            if ($("#hidden-workspace").find('.feed-item-single').length > 0) {
                $("#feed-items").prepend(html);
            }
            $("#hidden-workspace").empty();
        }
    }


</script>
